package com.ec.cr.service.impl;

import com.ec.cr.domain.dto.ManufacturerRatioDTO;
import com.ec.cr.domain.dto.PriceTrendDTO;
import com.ec.cr.domain.dto.StatsDTO;
import com.ec.cr.domain.entity.MedicineInfo;
import com.ec.cr.mapper.MedicineInfoMapper;
import com.ec.cr.service.MedicineInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MedicineInfoServiceImpl implements MedicineInfoService {

    @Autowired
    private MedicineInfoMapper medicineInfoMapper;

    @Override
    public List<MedicineInfo> searchByName(String keyword) {
        return medicineInfoMapper.searchByName(keyword);
    }

    @Override
    public Map<String, Object> selectPageList(int page, int pageSize, String name) {
        int offset = (page - 1) * pageSize;
        List<MedicineInfo> list = medicineInfoMapper.selectPageList(name, pageSize, offset);
        long count = medicineInfoMapper.countRecords(name);
        Map<String, Object> result = new HashMap<>();
        result.put("data", list);
        result.put("total", count);
        return result;
    }

    @Override
    public void insert(MedicineInfo drug) {
        medicineInfoMapper.insert(drug);
    }

    @Override
    public void update(MedicineInfo drug) {
        medicineInfoMapper.update(drug);
    }

    @Override
    public void delete(Long id) {
        medicineInfoMapper.delete(id);
    }

    /** 统计：总量 / 平均 / 最高 / 最低 */
    @Override
    public StatsDTO calcStats() {
        StatsDTO dto = new StatsDTO();
        // totalCount 用 countRecords(null) 或者单独写 countAll()
        dto.setTotalCount(medicineInfoMapper.countRecords(null));
        dto.setAvgPrice(medicineInfoMapper.avgPrice());
        dto.setMaxPrice(medicineInfoMapper.maxPrice());
        dto.setMinPrice(medicineInfoMapper.minPrice());
        return dto;
    }

    /** 价格趋势（按日平均价） */
    @Override
    public List<PriceTrendDTO> getPriceTrend() {
        return medicineInfoMapper.selectPriceTrend();
    }

    /** 生产厂家占比 */
    @Override
    public List<ManufacturerRatioDTO> getManufacturerRatio() {
        return medicineInfoMapper.selectManufacturerRatio();
    }

}
